package com.ruoyi.cms.controller.my;

import com.ruoyi.cms.domain.CmsArticleInputFile;
import com.ruoyi.cms.domain.CmsImage;
import com.ruoyi.cms.service.CmsArticleFileService;
import com.ruoyi.cms.service.ICmsArticleInputFileService;
import com.ruoyi.cms.service.ICmsImageService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.config.ServerConfig;
import org.apache.commons.io.FileUtils;
import org.apache.poi.openxml4j.opc.internal.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("cmsArticleFile")
public class CmsArticleFileController extends BaseController {

    @Autowired
    ICmsArticleInputFileService cmsArticleInputFileService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    RuoYiConfig ruoYiConfig;

    @Autowired
    CmsArticleFileService cmsArticleFileService;

    /**
     * 新增文章导入
     */
    @PreAuthorize("@ss.hasPermi('cms:article_file:add')")
    @Log(title = "文章导入", businessType = BusinessType.INSERT)
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestBody CmsArticleInputFile cmsArticleInputFile) throws FileNotFoundException {
        File file = FileUtils.getFile(cmsArticleInputFile.getFile().replace("/profile",RuoYiConfig.getProfile()));
        cmsArticleInputFileService.insertCmsArticleInputFile(cmsArticleInputFile);
        cmsArticleFileService.input(file,cmsArticleInputFile);
        return toAjax(1);
    }


    @Autowired
    ICmsImageService iCmsImageService;

    @PostMapping("/imagesUploads")
    public AjaxResult imagesUploads() throws IOException {
        String path = "D:\\文档\\个人\\分享数据\\图片2";

        List<String> allFiles = new ArrayList<>();
        File directory = new File(path);

        if (!directory.exists() || !directory.isDirectory()) {
            System.out.println("路径无效或不是目录");
            return AjaxResult.error("路径无效或不是目录");
        }

        listAllFiles(directory, allFiles);

        for(String temp : allFiles) {
            CmsImage image = new CmsImage();
            image.setLocalFilePath(temp);
            String fileName = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), getMultipartFileByPath(temp));
            image.setUrl(serverConfig.getUrl() + fileName);
            iCmsImageService.insertCmsImage(image);
        }

        return AjaxResult.success();
    }

    private static void listAllFiles(File dir, List<String> fileList) {
        File[] files = dir.listFiles();
        if (files == null) return; // 处理权限问题导致的空指针

        for (File file : files) {
            if (file.isDirectory()) {
                listAllFiles(file, fileList); // 递归处理子目录 ‌:ml-citation{ref="1,3" data="citationList"}
            } else {
                fileList.add(file.getAbsolutePath()); // 添加文件路径 ‌:ml-citation{ref="5,7" data="citationList"}
            }
        }
    }

    private static MultipartFile getMultipartFileByPath(String filePath) throws IOException {
        File file = new File(filePath);
        try (FileInputStream input = new FileInputStream(file)) {
            return new MockMultipartFile(
                    "file",                  // 表单字段名
                    file.getName(),          // 原始文件名
                    null,
                    input
            );
        }
    }

}
